from flask import Flask, jsonify
from flask_cors import CORS
from werkzeug.exceptions import RequestEntityTooLarge, HTTPException

from config.settings import (
    SERVER_HOST, SERVER_PORT, DEBUG, 
    UPLOAD_FOLDER, COMPRESSED_FOLDER, CONVERTED_FOLDER, LOG_DIR,
    MAX_FILE_SIZE, MAX_FILES_COUNT, FILE_RETENTION_DAYS, LOG_RETENTION_DAYS
)
from utils.logger import logger
from modules.compress import compress_bp
from modules.convert import convert_bp
from modules.cleanup import start_cleanup_thread

# 创建Flask应用
app = Flask(__name__)
CORS(app)  # 启用跨域请求支持

# 注册蓝图
app.register_blueprint(compress_bp)
app.register_blueprint(convert_bp)

# 错误处理器
@app.errorhandler(RequestEntityTooLarge)
def handle_request_too_large(error):
    logger.error(f"请求实体过大: {error}")
    return jsonify({'error': f'文件大小超过限制 (每个文件最大 {MAX_FILE_SIZE / (1024 * 1024):.1f}MB，最多 {MAX_FILES_COUNT} 个文件)'}), 413

@app.errorhandler(Exception)
def handle_unexpected_error(error):
    if isinstance(error, HTTPException):
        return error
    
    logger.error(f"未预期的错误: {error}")
    logger.error(traceback.format_exc())
    return jsonify({'error': '服务器内部错误'}), 500

@app.route('/api/health', methods=['GET'])
def health_check():
    logger.debug("健康检查请求")
    return jsonify({
        'status': 'ok', 
        'message': 'Server is running',
        'timestamp': datetime.now().isoformat(),
        'upload_dir_exists': os.path.exists(UPLOAD_FOLDER),
        'compressed_dir_exists': os.path.exists(COMPRESSED_FOLDER),
        'converted_dir_exists': os.path.exists(CONVERTED_FOLDER)
    })

@app.route('/api/logs', methods=['GET'])
def get_logs():
    """获取最近的日志（仅供开发调试使用）"""
    try:
        lines = request.args.get('lines', default=100, type=int)
        log_file = os.path.join(LOG_DIR, f'app_{datetime.now().strftime("%Y%m%d")}.log')
        with open(log_file, 'r', encoding='utf-8') as f:
            log_content = f.readlines()
        return jsonify({'logs': log_content[-lines:]})
    except Exception as e:
        logger.error(f"获取日志时出错: {str(e)}")
        return jsonify({'error': '无法获取日志'}), 500

if __name__ == '__main__':
    logger.info(f"服务器启动于 http://{SERVER_HOST}:{SERVER_PORT}")
    logger.info(f"上传目录: {UPLOAD_FOLDER}")
    logger.info(f"压缩文件目录: {COMPRESSED_FOLDER}")
    logger.info(f"格式转换文件目录: {CONVERTED_FOLDER}")
    logger.info(f"日志目录: {LOG_DIR}")
    logger.info(f"每个文件最大上传大小: {MAX_FILE_SIZE / (1024 * 1024):.1f}MB")
    logger.info(f"单次最大上传文件数: {MAX_FILES_COUNT}")
    logger.info(f"业务文件保留天数: {FILE_RETENTION_DAYS} 天")
    logger.info(f"日志文件保留天数: {LOG_RETENTION_DAYS} 天")
    
    # 启动文件清理线程
    cleanup_thread = start_cleanup_thread()
    
    app.run(debug=DEBUG, host=SERVER_HOST, port=SERVER_PORT)